#include "InfoPanel.h"
#include <QPainter>
#include <QColor>
#include <QBrush>
#include <QImage>
#include "Ptr.hpp"



using namespace OOPUtils;



InfoPanel::InfoPanel (QWidget * parent)
: QWidget (parent), _pWork (NULL)
{
  _ui.setupUi (this);
}

void InfoPanel::setWork (Ptr< Work > pWork)
{
	if (_pWork != NULL) {
		disconnect (_pWork->getViewportUI (),
				SIGNAL(mouseMoved(QMouseEvent *)), this,
				SLOT(canvasMouseMoved(QMouseEvent *)));
	}
	if (pWork == NULL) {
		_ui.lbWidth->setText ("");
		_ui.lbHeight->setText ("");
		_ui.lbColor->setText ("");
		_ui.lbFormat->setText ("");
		return;
	}
	_pWork = pWork;
	connect (_pWork->getViewportUI (), SIGNAL(mouseMoved(QMouseEvent *)),
			this, SLOT(canvasMouseMoved(QMouseEvent *)));
	Ptr< Document > pDoc = _pWork->getDoc ();
	_ui.lbWidth->setText (QString ("%1").arg (pDoc->getCanvasWidth ()));
	_ui.lbHeight->setText (QString ("%1").arg (pDoc->getCanvasHeight ()));
	switch (pDoc->getFormat ())
	{
	case QImage::Format_ARGB32:
		_ui.lbFormat->setText ("ARGB32"); break;
	case QImage::Format_RGB32:
		_ui.lbFormat->setText ("RGB32"); break;
	case QImage::Format_Indexed8:
		_ui.lbFormat->setText ("Gray8"); break;
	default:
		_ui.lbFormat->setText ("Unknown format");
	}
}

void InfoPanel::canvasMouseMoved (QMouseEvent * event)
{
	QRect paintRegion = _pWork->getViewportCtrl ()->getPaintRegion ();
	QRect imageRegion = _pWork->getViewportCtrl ()->getImageRegion ();
	QPoint loc = _pWork->getViewportCtrl ()->viewportToImage (event->pos ());
	Ptr< QImage > pImage = _pWork->getDoc ()->getTempPreview ();
	if (!paintRegion.contains (event->pos ())) {
		_ui.lbColor->setText ("");
		_ui.histogramPreview->setStyleSheet("");
		return;
	}
	if (_pWork->getDoc ()->isPreviewMode ()) {
		loc -= imageRegion.topLeft ();
	}
	QRgb c = pImage->pixel (loc);
	QString colorString = QString ("%1, %2, %3, %4").arg (qRed (c))
		.arg (qGreen (c)).arg (qBlue (c)).arg (qAlpha (c));
	_ui.lbColor->setText (colorString);
	_ui.histogramPreview->setStyleSheet(QString(
		"background-color: rgba(") + colorString + ");");
}
